<?php

namespace app\api\controller\zsdl;

use app\common\controller\Api;

use app\admin\model\exchange\Admin as AdminModel;
use app\admin\model\zs\dl\Exchangerecord as ExchangeRecordModel;
use app\admin\model\zs\dl\Prizerecord as RecordModel;
use app\admin\model\User as UserModel;
use app\admin\model\zs\dl\User as ZsdlUserModel;

use think\Db;

/**
 * 示例接口
 */
class Admin extends Api
{


    // 无需登录的接口,*表示全部
    protected $noNeedLogin = ['login','exchange','getExchangeData'];
    // 无需鉴权的接口,*表示全部
    protected $noNeedRight = ['*'];

    // 管理员加密
    protected $slat = "asdfghjkl";

    public function login()
    {
        $username = $this->request->post('username');
        $password = $this->request->post('password');
        $admin = AdminModel::where('account', $username)->where('status', 1)->find();
        if (!$admin) {
            $this->error('用户不存在');
        }

        if ($admin->status != 1) {
            $this->error('用户被禁用');
        }

        if ($admin->password !== $password) {
            $this->error('密码错误');
        }

        // 更新用户信息，登录时间，登录ip
        $admin->last_login_time = time();
        $admin->last_login_ip = $this->request->ip();
        $admin->save();

        $this->success('登录成功', [
            'admin_id' => $admin->id,
            'admin_name' => $admin->name,
        ]);
    }

    // 核销验证码
    public function exchange()
    {
        $slat = $this->request->post('slat');
        if (!$slat || $slat != $this->slat) {
            $this->error('请登录');
        }
        $code = $this->request->post('code');
        $admin_id = $this->request->post('admin_id');
        if (!$code) {
            $this->error('请输入核销码');
        }
        if (!$admin_id) {
            $this->error('请登录');
        }

        // 核销码格式为user_id-openid
        if (strpos($code, '-') === false) {
            $this->error('核销码错误');
        }

        /**
         * 查找第一个'-'的位置并分割字符串
         * @var int $split_pos 分割位置
         * @var string $user_id 用户ID
         * @var string $openid 用户的openid
         */
        $split_pos = strpos($code, '-');
        $user_id = substr($code, 0, $split_pos);
        $openid = substr($code, $split_pos + 1);
        if (!$user_id || !$openid) {
            $this->error('核销码错误');
        }



        $zsdl_user = ZsdlUserModel::where("openid", $openid)->find();
        if (!$zsdl_user) {
            $this->error('用户不存在');
        }

        $light_num = $zsdl_user->videoNum + $zsdl_user->lightNum;
        if ($light_num < 8) {
            $this->error('用户未点亮全部地标，无法兑换奖品');
        }

        // 查询用户中奖记录
        $record = RecordModel::where("openid", $openid)
        ->with(["prize"])->select();
        if (empty($record)) {
            $this->error('未找到中奖记录');
        }

        // 判断是否已经核销
        foreach ($record as $item) {
            if ($item->status == 1) {
                $this->error('用户已经兑换过奖品，无法重复兑换');
            }
        }

        $record_ids = [];
        $prize_ids = [];
        // 更新中奖记录状态，添加核销记录
        foreach ($record as $item) {
            $record_ids[] = $item->id;
            $prize_ids[] = [
                'prize_record_id' => $item->id,
                'admin_id' => $admin_id,
                'createtime' => time(),
            ];
        }

        $exchangeRecord = new ExchangeRecordModel();
        Db::startTrans();
        try {
            // 更新中奖记录状态
            RecordModel::where("id", "in", $record_ids)->update(["status" => 1]);
            // 添加核销记录
            $exchangeRecord->saveAll($prize_ids);
            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
            $this->error('核销失败',$e->getMessage());
        }
        $this->success('奖品核销成功',$record);
    }

    // 获取核销记录
    public function getExchangeData()
    {
        $slat = $this->request->post('slat');
        if (!$slat || $slat != $this->slat) {
            $this->error('请登录');
        }
        $admin_id = $this->request->post('admin_id');
        if (!$admin_id) {
            $this->error('请登录');
        }
        $recordModel = new ExchangeRecordModel();
        $datas = $recordModel->where("admin_id",$admin_id)->with(["prizerecord"])->select();
        $this->success('获取成功', $datas);
    }

  
}
